<template>
  <!-- 评论的组件 -->
  <div class="post-comment">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="优质评论将会被优先展示"
      show-word-limit
    />
    <van-button
      class="post-btn"
      size="small"
      @click="onAddComment()"
      :disabled="message.length === 0"
      >发布</van-button
    >
  </div>
</template>

<script>
import { addCommentAPI } from '../../../api/index.js'
export default {
  name: 'CommentPost',
  // 接收数据
  // 与props写法一样,在inject中定义的属性,就是provide中发送过来的参数
  // inject获取得到的参数,只能读取,不可修改
  inject: {
    articleIdG: {
      type: String,
      default: ''
    }
  },
  props: {
    targetId: {
      type: String,
      default: ''
    },
    artId: {
      type: String,
      default: null
    },
    commentList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      message: ''
    }
  },
  methods: {
    async onAddComment () {
      try {
        // 判空验证
        if (this.message.trim().length <= 0) {
          this.$toast('评论内容不能为空')
          return
        }
        // 调用接口 添加数据
        const res = await addCommentAPI({
          // target: 评论目标id    content : 评论内容   art_id :文章id,回复评论时需要,对文章进行评论不需要传这个参数
          target: this.targetId,
          content: this.message.trim(),
          art_id: this.artId
        })
        // 发布成功之后自动关闭弹出层  将发布内容显示到列表的顶部unshift 且清空文本框
        this.message = ''
        this.$emit('success', res.data.data.new_obj)
        this.$toast.success('评论发布成功')
      } catch (error) {
        console.log(error)
        this.$toast.fail('发布失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.post-comment {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
